package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.framework.ErrorCode;
import com.example.demo.framework.ResultData;
import com.example.demo.framework.base.BaseController;
import com.example.demo.framework.util.JodaUtil;
import com.example.demo.model.UserInfo;
import com.example.demo.repository.UserRepository;

/**
 * 登录
 * @author jc
 *
 */
@RestController
public class CommonController extends BaseController {


	@Autowired
	private UserRepository userRepository;

	/**
	 * 用户登录
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping("login")
	public Object login(String username, String password) {
		Map<String, Object> data = new HashMap<>();
		UserInfo user = userRepository.getByUsername(username);
		if (user == null || !password.equals(user.getPassword())) {
			return new ResultData(ErrorCode.ERROR_10001, null);
		}
		if(StringUtils.isNotEmpty(user.getToken())){
			if(JodaUtil.tokenIsOverdue(user.getTokenTime())){
				user.setToken(createToken());
				user.setTokenTime(JodaUtil.now());
			}else{
				user.setTokenTime(JodaUtil.now());
			}
		}else{
			user.setToken(createToken());
			user.setTokenTime(JodaUtil.now());
		}
		userRepository.save(user);
		data.put("user", user);
		return new ResultData(data);
	}
	
	/**
	 * 代理商注册
	 * @return
	 */
	@RequestMapping("register")
	public Object register(UserInfo user){
		Map<String, Object> data = new HashMap<>();
		UserInfo info=userRepository.getByUsername(user.getUsername());
		if (info!=null) {
			return new ResultData(ErrorCode.ERROR_10201, null);
		}else {
			user.setUserType(1);
			user.setUserLevel(1);
			user.setUserMoney(0D);
			user.setDiscount(1D);
			user.setuStatus(0);
			user.setSaleroom(0D);
			user.setRegTime(JodaUtil.now());
			userRepository.save(user);
		}
		return new ResultData(data);
	}
	
}
